package com.im.partchat.ui.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.im.partchat.R;
import com.im.partchat.adapter.MyFragmentPagerAdapter;
import com.im.partchat.base.BaseActivity;
import com.im.partchat.bean.eventbus.NagvationToLearn;
import com.im.partchat.topic.TopicFragment;
import com.im.partchat.ui.fragment.LearnFragment;
import com.im.partchat.ui.fragment.MainFragment;
import com.im.partchat.ui.fragment.MineFragment;
import com.im.partchat.utils.AppManager;
import com.im.partchat.utils.Navigation;
import com.im.partchat.widget.BottomNavigationViewEx;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;
import io.rong.imkit.RongContext;
import io.rong.imkit.RongIM;
import io.rong.imkit.fragment.ConversationListFragment;
import io.rong.imkit.manager.IUnReadMessageObserver;
import io.rong.imkit.widget.adapter.ConversationListAdapter;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.message.ContactNotificationMessage;
import q.rorbin.badgeview.Badge;
import q.rorbin.badgeview.QBadgeView;

public class MainActivity extends BaseActivity implements
        ViewPager.OnPageChangeListener,
        IUnReadMessageObserver {

    @BindView(R.id.viewPager)
    ViewPager viewPager;
    @BindView(R.id.navigation)
    BottomNavigationViewEx navigation;

    @BindView(R.id.ll_switch)
    LinearLayout llSwitch;
    @BindView(R.id.toolbar_txl)
    ImageButton imgContact;

    @BindView(R.id.tv_all_topic)
    TextView tvAllTopic;

    @BindView(R.id.tv_my_topic)
    TextView tvMyTopic;

    private MenuItem menuItem;
    private List<Fragment> fragmentList;

    /**
     * 会话列表的fragment
     */
    private ConversationListFragment mConversationListFragment;
    private Conversation.ConversationType[] mConversationsTypes;

    private Badge badge;


    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView(@Nullable Bundle savedInstanceState) {
        super.initView(savedInstanceState);

        navigation.enableAnimation(false);
        navigation.enableShiftingMode(false);
        navigation.enableItemShiftingMode(false);
        navigation.setSelectedItemId(R.id.navigation_main);

        navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
        initViewPager();
    }

    @Override
    protected void initToolbar() {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        if (toolbar == null)
            return;

        if (getSupportActionBar() == null) {
            setSupportActionBar(toolbar);
        }
        toolbar.setOnMenuItemClickListener(this);
        toolbar.setVisibility(View.GONE);
    }
    private void initViewPager() {
        fragmentList = new ArrayList<>();
        fragmentList.add(new MainFragment());
        fragmentList.add(new LearnFragment());
        fragmentList.add(new TopicFragment());
        fragmentList.add(initConversationList());
        fragmentList.add(new MineFragment());
        viewPager.setAdapter(new MyFragmentPagerAdapter(getSupportFragmentManager(), fragmentList));
        viewPager.setOnPageChangeListener(this);
        viewPager.setOffscreenPageLimit(5);

    }

    @OnClick({R.id.tv_my_topic, R.id.tv_all_topic, R.id.toolbar_txl})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_all_topic:

                break;
            case R.id.tv_my_topic:

                break;
            case R.id.toolbar_txl:
                Navigation.navigateContact();
                break;
        }
    }

    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
            = new BottomNavigationView.OnNavigationItemSelectedListener() {

        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            int positionId = getPositionByMenuId(item.getItemId());
            viewPager.setCurrentItem(positionId, true);

            return false;
        }

    };

    private int getPositionByMenuId(int position) {
        switch (position) {

            case R.id.navigation_main:
                return 0;
            case R.id.navigation_learn:
                return 1;

            case R.id.navigation_activity:
                return 2;

            case R.id.navigation_message:
                return 3;

            case R.id.navigation_mine:
                return 4;

            default:
                return 0;
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onMenuItemClick(MenuItem item) {
        if (item.getItemId() == R.id.main_setting) {
            Navigation.navigateSetting();
        } else if (item.getItemId() == R.id.action_add_friend) {

        } else if (item.getItemId() == R.id.action_fqql) {
            Navigation.navigateSelectFriends();
        }
        return super.onMenuItemClick(item);
    }
    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        String menuTitle = navigation.getMenu().getItem(position).getTitle().toString();
        setToolbarTitle(menuTitle);
        if (menuItem != null) {
            menuItem.setChecked(false);
        } else {
            navigation.getMenu().getItem(0).setChecked(false);
        }
        menuItem = navigation.getMenu().getItem(position);
        menuItem.setChecked(true);


        switch (position){

            case 0:
                toolbar.setVisibility(View.GONE);
                break;
            case 1:
                toolbar.getMenu().findItem(R.id.main_setting).setVisible(false);
                toolbar.getMenu().findItem(R.id.action_more).setVisible(false);
                setToolbarTitleVisable(true);
                llSwitch.setVisibility(View.GONE);
                imgContact.setVisibility(View.GONE);
                toolbar.setVisibility(View.VISIBLE);
                break;
            case 2:
                toolbar.getMenu().findItem(R.id.main_setting).setVisible(false);
                toolbar.getMenu().findItem(R.id.action_more).setVisible(false);
                llSwitch.setVisibility(View.VISIBLE);
                toolbar.setVisibility(View.VISIBLE);
                imgContact.setVisibility(View.GONE);
                setToolbarTitleVisable(false);
                break;

            case 3:
                toolbar.getMenu().findItem(R.id.main_setting).setVisible(false);
                toolbar.getMenu().findItem(R.id.action_more).setVisible(true);
                setToolbarTitleVisable(true);
                llSwitch.setVisibility(View.GONE);
                imgContact.setVisibility(View.VISIBLE);
                toolbar.setVisibility(View.VISIBLE);
                break;
            case 4:
                toolbar.getMenu().findItem(R.id.action_more).setVisible(false);
                toolbar.getMenu().findItem(R.id.main_setting).setVisible(true);
                setToolbarTitleVisable(true);
                imgContact.setVisibility(View.GONE);
                llSwitch.setVisibility(View.GONE);
                toolbar.setVisibility(View.VISIBLE);
                break;

        }

    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    private Badge addBadgeNumber(int position, int number) {
        // add badge
        return new QBadgeView(this)
                .setBadgeNumber(number)
                .setGravityOffset(12, 2, true)
                .bindTarget(navigation.getBottomNavigationItemView(position))
                .setOnDragStateChangedListener(new Badge.OnDragStateChangedListener() {
                    @Override
                    public void onDragStateChanged(int dragState, Badge badge, View targetView) {
                        if (Badge.OnDragStateChangedListener.STATE_SUCCEED == dragState)
                            Toast.makeText(MainActivity.this, "remove", Toast.LENGTH_SHORT).show();
                    }
                });
    }

    private Badge addBadgeNew(int position, String content) {
        return new QBadgeView(this)
                .setBadgeText(content)
                .setGravityOffset(12, 2, true)
                .bindTarget(navigation.getBottomNavigationItemView(position))
                .setOnDragStateChangedListener(null);
    }

    @Override
    public void onLoadDataSuccess(Object o, String flag) {

    }

    protected void initData() {
        final Conversation.ConversationType[] conversationTypes = {
                Conversation.ConversationType.PRIVATE,
                Conversation.ConversationType.GROUP, Conversation.ConversationType.SYSTEM,
                Conversation.ConversationType.PUBLIC_SERVICE, Conversation.ConversationType.APP_PUBLIC_SERVICE
        };

        RongIM.getInstance().addUnReadMessageCountChangedObserver(this, conversationTypes);
//        getConversationPush();// 获取 push 的 id 和 target
//        getPushMessage();
    }

    private Fragment initConversationList() {
        if (mConversationListFragment == null) {
            ConversationListFragment listFragment = new ConversationListFragment();
            listFragment.setAdapter(new ConversationListAdapter(RongContext.getInstance()));
            Uri uri = Uri.parse("rong://" + getApplicationInfo().packageName).buildUpon()
                    .appendPath("conversationlist")
                    .appendQueryParameter(Conversation.ConversationType.PRIVATE.getName(), "false") //设置私聊会话是否聚合显示
                    .appendQueryParameter(Conversation.ConversationType.GROUP.getName(), "false")//群组
                    .appendQueryParameter(Conversation.ConversationType.PUBLIC_SERVICE.getName(), "false")//公共服务号
                    .appendQueryParameter(Conversation.ConversationType.APP_PUBLIC_SERVICE.getName(), "false")//订阅号
                    .appendQueryParameter(Conversation.ConversationType.SYSTEM.getName(), "true")//系统
                    .build();
            mConversationsTypes = new Conversation.ConversationType[]{Conversation.ConversationType.PRIVATE,
                    Conversation.ConversationType.GROUP,
                    Conversation.ConversationType.PUBLIC_SERVICE,
                    Conversation.ConversationType.APP_PUBLIC_SERVICE,
                    Conversation.ConversationType.SYSTEM
            };
            listFragment.setUri(uri);
            mConversationListFragment = listFragment;
            return listFragment;
        } else {
            return mConversationListFragment;
        }
    }

    private void getConversationPush() {
        if (getIntent() != null && getIntent().hasExtra("PUSH_CONVERSATIONTYPE")
                && getIntent().hasExtra("PUSH_TARGETID")) {
            final String conversationType = getIntent().getStringExtra("PUSH_CONVERSATIONTYPE");
            final String targetId = getIntent().getStringExtra("PUSH_TARGETID");


            RongIM.getInstance().getConversation(Conversation.ConversationType.valueOf(conversationType), targetId, new RongIMClient.ResultCallback<Conversation>() {
                @Override
                public void onSuccess(Conversation conversation) {

                    if (conversation != null) {

                        if (conversation.getLatestMessage() instanceof ContactNotificationMessage) { //好友消息的push
//                            startActivity(new Intent(MainActivity.this, NewFriendListActivity.class));
                        } else {
                            Uri uri = Uri.parse("rong://" + getApplicationInfo().packageName).buildUpon().appendPath("conversation")
                                    .appendPath(conversationType).appendQueryParameter("targetId", targetId).build();
                            Intent intent = new Intent(Intent.ACTION_VIEW);
                            intent.setData(uri);
                            startActivity(intent);
                        }
                    }
                }

                @Override
                public void onError(RongIMClient.ErrorCode e) {

                }
            });
        }
    }

    @Override
    public void onCountChanged(int count) {
        if (count == 0) {

        } else if (count > 0 && count < 100) {
            addBadgeNumber(3, count);
        } else {
            addBadgeNew(3, "99+");
        }
    }

    /**
     * 得到不落地 push 消息
     */
//    private void getPushMessage() {
//        Intent intent = getIntent();
//        if (intent != null && intent.getData() != null
//                && intent.getData().getScheme().equals("rong")) {
//            String path = intent.getData().getPath();
//            if (path.contains("push_message")) {
//                SharedPreferences sharedPreferences = getSharedPreferences("config", MODE_PRIVATE);
//                String cacheToken = sharedPreferences.getString("loginToken", "");
//                if (TextUtils.isEmpty(cacheToken)) {
//                    startActivity(new Intent(MainActivity.this, LoginActivity.class));
//                } else {
//                    if (!RongIM.getInstance().getCurrentConnectionStatus().equals(RongIMClient.ConnectionStatusListener.ConnectionStatus.CONNECTED)) {
//                        LoadDialog.show(mContext);
//                        RongIM.connect(cacheToken, new RongIMClient.ConnectCallback() {
//                            @Override
//                            public void onTokenIncorrect() {
//                                LoadDialog.dismiss(mContext);
//                            }
//
//                            @Override
//                            public void onSuccess(String s) {
//                                LoadDialog.dismiss(mContext);
//                            }
//
//                            @Override
//                            public void onError(RongIMClient.ErrorCode e) {
//                                LoadDialog.dismiss(mContext);
//                            }
//                        });
//                    }
//                }
//            }
//        }
//    }


    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEventMainThread(NagvationToLearn nagvationToLearn) {
        viewPager.setCurrentItem(1);
    }
    @Override
    public void onBackPressed() {
        exitBy2Click();
    }

    /**
     * 双击退出函数
     */
    private static Boolean isExit = false;

    private void exitBy2Click() {
        Timer tExit = null;
        if (isExit == false) {
            isExit = true;

            showToast("再按一次返回桌面");
            tExit = new Timer();
            tExit.schedule(new TimerTask() {
                @Override
                public void run() {
                    isExit = false;
                }
            }, 2000);

        } else {
            AppManager.getAppManager().finishAllActivity();
            System.exit(0);
        }
    }

    @Override
    protected boolean isRegisterEventBus() {
        return true;
    }
}
